package cn.hznc.controller.service.order;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.collection.CollectionUtil;
import cn.hutool.core.util.ObjectUtil;
import cn.hznc.configuration.CellRowHeightStyleStrategy;
import cn.hznc.configuration.CellStyleStrategy;
import cn.hznc.constant.CommonConstant;
import cn.hznc.constant.OrderStatusEnum;
import cn.hznc.constant.SortOrderEnum;
import cn.hznc.controller.service.QuerySqlServerService;
import cn.hznc.controller.service.order.logic.OrderDo;
import cn.hznc.controller.service.program.SubProgramManageService;
import cn.hznc.controller.service.sharefile.ShareFileService;
import cn.hznc.domain.entity.*;
import cn.hznc.domain.entity.common.EquipmentSubprogramMappingEntity;
import cn.hznc.domain.request.common.QueryCondition;
import cn.hznc.domain.request.order.*;
import cn.hznc.domain.response.PageResult;
import cn.hznc.dto.*;
import cn.hznc.exception.*;
import cn.hznc.mapper.*;
import cn.hznc.repository.*;
import cn.hznc.controller.service.order.logic.OrderBomDo;
import cn.hznc.controller.service.order.logic.OrderBomLogic;
import cn.hznc.controller.task.InventoryTask;
import cn.hznc.utils.CommonUtil;
import cn.hznc.utils.EasyExcelUtil;
import cn.hznc.utils.UUIDUtil;
import cn.hznc.vo.*;
import com.alibaba.excel.EasyExcel;
import com.alibaba.excel.ExcelWriter;
import com.alibaba.excel.write.metadata.WriteSheet;
import com.alibaba.excel.write.metadata.fill.FillConfig;
import com.alibaba.excel.write.metadata.fill.FillWrapper;
import com.alibaba.excel.write.metadata.style.WriteCellStyle;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.github.pagehelper.util.StringUtil;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.core.io.ClassPathResource;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.InputStream;
import java.math.BigDecimal;
import java.net.URLEncoder;
import java.util.*;
import java.util.stream.Collectors;

/**
 * 工单管理服务
 *
 * @Author Administrator
 * @Date 2023/3/20 10:26
 */
@Service
@Slf4j
public class OrderManageService {

    @Resource
    private WarehouseRespository warehouseRespository;

    @Resource
    private OrderMapper orderMapper;

    @Resource
    private ProcessMapper processMapper;

    @Resource
    private ProcessCraftMapper processCraftMapper;

    @Resource
    private MachineToolTaskRespository machineToolTaskRespository;

    @Resource
    private ProductionRespository productionRespository;

    @Resource
    private OrderRespository orderRespository;

    @Resource
    private QuerySqlServerService querySqlServerService;

    @Resource
    private OrderCraftMapper orderCraftMapper;

    @Resource
    private OrderBomMapper orderBomMapper;

    @Resource
    private SubProgramRespository subProgramRespository;

    @Resource
    private ProgramMapper programMapper;

    @Resource
    private OrderProgramMapper orderProgramMapper;

    @Resource
    private OrderProgramRepository orderProgramRepository;

    @Resource
    private ProductionBomMapper productionBomMapper;

    @Resource
    private ProductionMapper productionMapper;

    @Resource
    private ProcessRepository processRepository;

    @Resource
    private ProgramRepository programRepository;

    @Resource
    private ProcessCraftProgramMapper processCraftProgramMapper;

    @Resource
    private SubProgramManageService subProgramManageService;

    @Resource
    private EquipmentSubprogramMappingMapper equipmentSubprogramMappingMapper;

    @Resource
    private ProductionProcessMapper productionProcessMapper;

    @Resource
    private SubProgramMapper subProgramMapper;

    @Resource
    private EquipmentSubprogramMappingMapper mappingMapper;


    @Resource
    private ShareFileService shareFileService;

    @Resource
    private InventoryTask inventoryTask;

    @Resource
    private MachineToolDataLogRepository machineToolDataLogRepository;

    @Resource
    private MachineToolTaskMapper machineToolTaskMapper;


    /**
     * 字段白名单----建议单独弄一个去做
     */
    private static final HashMap<String, String> fieldMap = new HashMap<>();

    private static final HashMap<String, String> sortEnumMap = new HashMap<>();

    private static final HashMap<String, String> sortEnumMap1 = new HashMap<>();

    static {
        fieldMap.put("taskId", "task_id");
        fieldMap.put("materialNo", "material_no");
        fieldMap.put("productionName", "production_name");
        fieldMap.put("priority", "priority");
        fieldMap.put("productionNum", "production_num");
        fieldMap.put("finishTime", "finish_time");
        fieldMap.put("orderStatus", "order_status");
        fieldMap.put("status", "status");
        fieldMap.put("abutmentStatus", "abutment_status");
        fieldMap.put("releaseTime", "release_time");

        sortEnumMap.put("taskId", "TaskId");
        sortEnumMap.put("materialNo", "MaterialNo");
        sortEnumMap.put("heavy", "Heavy");
        sortEnumMap.put("sortPriority", "SortPriority");
        sortEnumMap.put("productionNum", "ProductionNum");
        sortEnumMap.put("planNumber", "PlanNumber");
        sortEnumMap.put("realNumber", "RealNumber");
        sortEnumMap.put("finishTime", "FinishTime");
        sortEnumMap.put("releaseTime", "ReleaseTime");

        sortEnumMap1.put("inboundTime", "InboundTime");
        sortEnumMap1.put("standTime", "StandTime");
        sortEnumMap1.put("cycleTime", "CycleTime");
        sortEnumMap1.put("inCraftName", "InCraftName");
    }

//    /**
//     * 查询工单
//     *
//     * @param queryProcessReq queryProcessReq
//     * @return
//     */
//    public PageResult<OrderEntity> queryOrderList(QueryOrderReq queryProcessReq) {
//        List<QueryCondition> queryConditions = new ArrayList<>();
//        if (!CollectionUtil.isEmpty(queryProcessReq.getQueryConditions())) {
//            queryConditions = queryProcessReq.getQueryConditions().stream().
//                    filter(queryCondition -> fieldMap.getOrDefault(queryCondition.getKey(), null) != null).
//                    collect(Collectors.toList());
//        }
//        PageHelper.startPage(queryProcessReq.getPageNum(), queryProcessReq.getPageSize());
//        QueryWrapper<OrderEntity> wrapper = buildQueryWrapper(queryConditions);
//        PageInfo<OrderEntity> pageInfo = new PageInfo<>(orderMapper.selectList(wrapper));
//        return new PageResult<>(pageInfo.getList(), pageInfo.getTotal());
//    }

    /**
     * 查询工单
     *
     * @param queryProcessReq queryProcessReq
     * @return
     */
    public PageResult<OrderEntity> queryOrderList(QueryOrderReqReload queryProcessReq) {
        List<QueryCondition> queryConditions = new ArrayList<>();
        List<OrderEntity> resultList = new ArrayList<>();
        List<OrderEntity> pageList = new ArrayList<>();
        boolean flag = false;
        if (!CollectionUtil.isEmpty(queryProcessReq.getQueryConditions())) {
            queryConditions = queryProcessReq.getQueryConditions().stream().
                    filter(queryCondition -> fieldMap.getOrDefault(queryCondition.getKey(), null) != null).
                    collect(Collectors.toList());
        }
        QueryWrapper<OrderEntity> wrapper = buildQueryWrapper(queryConditions);
        if(ObjectUtil.isNotNull(queryProcessReq.getFlag())){
            if (queryProcessReq.getFlag()){
                wrapper.ne("abutment_status" , 9);
            }
        }
        resultList = orderMapper.selectList(wrapper);
        //按照物料编码数组模糊查询
        if (CollectionUtil.isNotEmpty(queryProcessReq.getMaterialNos()) && CollectionUtil.isNotEmpty(resultList)) {
            List<OrderEntity> filterList = new ArrayList<>();
            for (String materialNo : queryProcessReq.getMaterialNos()) {
                List<OrderEntity> copyResultList = resultList;
                filterList.addAll(copyResultList.stream().filter(orderEntity -> StringUtils.isNotEmpty(orderEntity.getMaterialNo()) && orderEntity.getMaterialNo().contains(materialNo)).collect(Collectors.toList()));
            }
            resultList = filterList.stream().distinct().collect(Collectors.toList());
        }
        SortCondition sortCondition = queryProcessReq.getSortCondition();
        //对条件查询的orderEntities排序
        if (CollectionUtil.isNotEmpty(resultList) && ObjectUtil.isNotNull(sortCondition)) {
            if (sortEnumMap.containsKey(sortCondition.getSortColumn())) {
                SortOrderEnum sortOrderEnum = SortOrderEnum.valueOf(sortEnumMap.getOrDefault(sortCondition.getSortColumn(), null));
                resultList = sortOrderEnum.sortByCondition(resultList, sortCondition.getSortType());
            }
        }
        //手动分页
        if (CollectionUtil.isNotEmpty(resultList)) {
            //根据是否有工序的搜索条件来决定分页时机
            if(StringUtil.isNotEmpty(queryProcessReq.getInCraftNames()) || StringUtils.isNotBlank(sortCondition.getSortColumn())){
                pageList = resultList;
                flag = true;
            }else {
                pageList = CommonUtil.pageList(resultList, queryProcessReq.getPageNum(), queryProcessReq.getPageSize());
            }
//
            QueryWrapper<OrderCraftEntity> orderCraftWrapper = new QueryWrapper<>();
            orderCraftWrapper.in("task_id", pageList.stream().map(OrderEntity::getTaskId).collect(Collectors.toList()));
            List<OrderCraftEntity> existOrderCraft = orderCraftMapper.selectList(orderCraftWrapper);
            Map<String , OrderCraftEntity> taskIdOrderCraftEntityMap = new HashMap<>();
            if(CollectionUtil.isNotEmpty(existOrderCraft)){
                taskIdOrderCraftEntityMap = existOrderCraft.stream().collect(Collectors.toMap(OrderCraftEntity::getTaskId , OrderCraftEntity->OrderCraftEntity));
            }
            //处理显示在制工单信息
            for (OrderEntity orderEntity : pageList) {
//                QueryWrapper<OrderCraftEntity> orderCraftWrapper = new QueryWrapper<>();
//                orderCraftWrapper.eq("task_id", orderEntity.getTaskId());
//                OrderCraftEntity orderCraftEntity = orderCraftMapper.selectOne(orderCraftWrapper);
                List<InCraftVo> inCraftVos = new ArrayList<>();
                OrderCraftEntity orderCraftEntity = taskIdOrderCraftEntityMap.get(orderEntity.getTaskId());
                if (ObjectUtil.isNotNull(orderCraftEntity) && StringUtil.isNotEmpty(orderCraftEntity.getCraftParam()) && !"[]".equals(orderCraftEntity.getCraftParam())) {
                    List<CraftParamVo> craftParamVos = JSONArray.parseArray(orderCraftEntity.getCraftParam(), CraftParamVo.class).stream().
                            sorted(Comparator.comparingInt(CraftParamVo::getSeq)).
                            collect(Collectors.toList());
                    if (CollectionUtil.isNotEmpty(craftParamVos)) {
                        craftParamVos.forEach(craftParamVo -> {
                            if (ObjectUtil.isNotNull(craftParamVo.getStatus()) && craftParamVo.getStatus() == 5) {
                                InCraftVo inCraftVo = new InCraftVo();
                                inCraftVo.setInCraftName(craftParamVo.getName());
                                inCraftVo.setInCraftSeq(craftParamVo.getSeq());
                                inCraftVo.setStartTime(craftParamVo.getStartTime());
                                inCraftVo.setQualifiedNumber(craftParamVo.getQualifiedNumber());
                                inCraftVo.setEndTime(craftParamVo.getEndTime());
                                inCraftVo.setInboundNumber(craftParamVo.getInboundNumber());
                                inCraftVo.setRejectedNumber(craftParamVo.getRejectedNumber());
                                inCraftVo.setInProcessNumber(craftParamVo.getInProcessNumber());
                                inCraftVo.setBz(craftParamVo.getBz());
                                inCraftVos.add(inCraftVo);
                            }
                        });
                    }
                    if (CollectionUtil.isNotEmpty(inCraftVos)) {
                        orderEntity.setInCraftName(inCraftVos.get(0).getInCraftName());
                    }
                    orderEntity.setInCrafts(inCraftVos);
                }
            }
            //根据在制工序名称模糊搜索
            if (StringUtil.isNotEmpty(queryProcessReq.getInCraftNames())) {
                pageList = pageList
                        .stream()
                        .filter(orderEntity -> ObjectUtil.isNotNull(orderEntity.getInCraftName()) && orderEntity.getInCraftName().contains(queryProcessReq.getInCraftNames()))
                        .collect(Collectors.toList());
            }
            //根据工序周期 工序停滞时间 转入时间 工序名排序
            if(StringUtils.isNotBlank(sortCondition.getSortColumn())){
                pageList = sortOrderEntity(pageList, sortCondition);
            }
            //是否需要分页
            if(flag){
                pageList = CommonUtil.pageList(pageList , queryProcessReq.getPageNum() , queryProcessReq.getPageSize());
            }
            //返回机床工序数组
            pageList.forEach(orderEntity -> {
                orderEntity.setCraftParamVos(queryOrderCraftDetailReload(orderEntity.getTaskId()));
            });

        }
        return new PageResult<>(pageList, (long) resultList.size());
    }

    private List<OrderEntity> sortOrderEntity(List<OrderEntity> resultList, SortCondition sortCondition) {
        Date date = new Date();
        long currentTime = date.getTime();
        resultList.forEach(orderEntity -> {
            if (CollectionUtil.isNotEmpty(orderEntity.getInCrafts())) {
                List<InCraftVo> inCraftVos = orderEntity.getInCrafts().stream().sorted(Comparator.comparing(InCraftVo::getInCraftSeq)).collect(Collectors.toList());
                InCraftVo inCraftVo = inCraftVos.get(0);
                //工序周期
                if(ObjectUtil.isNotNull(orderEntity.getReleaseTime())){
                    long releaseTime = orderEntity.getReleaseTime().getTime();
                    orderEntity.setCycleTime(currentTime - releaseTime);
                }
                //工序停滞时间
                if(ObjectUtil.isNotNull(inCraftVo.getStartTime())){
                    long inboundTime = inCraftVo.getStartTime().getTime();
                    orderEntity.setStandTime(currentTime - inboundTime);
                    //转入时间
                    orderEntity.setInboundTime(inboundTime);
                }
                orderEntity.setInCraftName(inCraftVo.getInCraftName());
            }
        });
        if (ObjectUtil.isNotNull(sortCondition)) {
            if (sortEnumMap1.containsKey(sortCondition.getSortColumn())) {
                SortOrderEnum sortOrderEnum = SortOrderEnum.valueOf(sortEnumMap1.getOrDefault(sortCondition.getSortColumn(), null));
                return sortOrderEnum.sortByCondition(resultList, sortCondition.getSortType());
            }
        }
        return resultList;
    }


    /**
     * 查询工单
     *
     * @param queryProcessReq queryProcessReq
     * @return
     */
    public List<OrderEntity> queryOrderListReload(QueryOrderReq queryProcessReq) {
        List<QueryCondition> queryConditions = new ArrayList<>();
        List<OrderEntity> resultList = new ArrayList<>();
        if (!CollectionUtil.isEmpty(queryProcessReq.getQueryConditions())) {
            queryConditions = queryProcessReq.getQueryConditions().stream().
                    filter(queryCondition -> fieldMap.getOrDefault(queryCondition.getKey(), null) != null).
                    collect(Collectors.toList());
        }
        QueryWrapper<OrderEntity> wrapper = buildQueryWrapper(queryConditions);
        resultList = orderMapper.selectList(wrapper);
        SortCondition sortCondition = queryProcessReq.getSortCondition();
        //对条件查询的orderEntities排序
        if (CollectionUtil.isNotEmpty(resultList) && ObjectUtil.isNotNull(sortCondition)) {
            //排序字段白名单
//            sortConditions = queryProcessReq.getSortCondition().stream().
//                    filter(sortCondition -> sortEnumMap.getOrDefault(sortCondition.getSortColumn(), null) != null).
//                    collect(Collectors.toList());
            //递归排序
            //resultList = recursiveSort(resultList , 0 , sortConditions);
            if (sortEnumMap.containsKey(sortCondition.getSortColumn())) {
                SortOrderEnum sortOrderEnum = SortOrderEnum.valueOf(sortEnumMap.getOrDefault(sortCondition.getSortColumn(), null));
                resultList = sortOrderEnum.sortByCondition(resultList, sortCondition.getSortType());
            }
        }
        return resultList;
    }

    private List<OrderEntity> recursiveSort(List<OrderEntity> orderEntities, int index, List<SortCondition> sortConditions) {
        if (index == sortConditions.size()) {
            return orderEntities;
        }
        SortCondition sortCondition = sortConditions.get(index);
        SortOrderEnum sortOrderEnum = SortOrderEnum.valueOf(sortEnumMap.getOrDefault(sortCondition.getSortColumn(), null));
        List<OrderEntity> sortedOrderEntities = sortOrderEnum.sortByCondition(orderEntities, sortCondition.getSortType());
        index++;
        return recursiveSort(sortedOrderEntities, index, sortConditions);
    }

    private QueryWrapper<OrderEntity> buildQueryWrapper(List<QueryCondition> queryConditions) {
        QueryWrapper<OrderEntity> wrapper = new QueryWrapper<>();
        for (QueryCondition queryCondition : queryConditions) {
            if (CommonConstant.EQUALS_CONDITION_CONST.equals(queryCondition.getCondition())) {
                wrapper.eq(fieldMap.get(queryCondition.getKey()), queryCondition.getValue());
            }
            if (CommonConstant.LIKE_CONDITION_CONST.equals(queryCondition.getCondition())) {
                wrapper.like(fieldMap.get(queryCondition.getKey()), queryCondition.getValue());
            }
            if (CommonConstant.BETWEEN_CONDITION_CONST.equals(queryCondition.getCondition())) {
                wrapper.between(fieldMap.get(queryCondition.getKey()), queryCondition.getStartValue(), queryCondition.getEndValue());
            }
            if (CommonConstant.NOT_EQUALS_CONDITION_CONST.equals(queryCondition.getCondition())) {
                wrapper.ne(fieldMap.get(queryCondition.getKey()), queryCondition.getValue());
            }
        }
        return wrapper;
    }

    /**
     * 编辑工单基本信息字段
     *
     * @param editOrderReq editOrderReq
     * @return
     * @throws ToolManageException
     */
    public Boolean editorOrder(EditOrderReq editOrderReq) throws ToolManageException {
        OrderEntity orderEntity = orderMapper.selectById(editOrderReq.getId());
        AssertExUtil.assertNoNull(orderEntity, ToolManageEx.ORDER_NO_EXIST);
        // 复制参数，更新
        orderEntity.setProductionName(editOrderReq.getProductionName());
        orderEntity.setPriority(editOrderReq.getPriority());
        orderEntity.setHeavy(editOrderReq.getHeavy());
        orderEntity.setPlanNumber(editOrderReq.getPlanNumber());
        orderEntity.setStorageSpace(editOrderReq.getStorageSpace());
        orderEntity.setVersion(ObjectUtil.isNull(editOrderReq.getVersion()) ? CommonConstant.INIT_VERSION : editOrderReq.getVersion());
        orderEntity.setFinishTime(editOrderReq.getFinishTime());
        orderMapper.updateById(orderEntity);
        return Boolean.TRUE;
    }

    /**
     * 创建工单
     *
     * @param createOrderReq createOrderReq
     */
    @Transactional
    public Boolean createOrder(CreateOrderReq createOrderReq) throws ToolManageException {
        //校验工单号唯一性
        QueryWrapper<OrderEntity> wrapper = new QueryWrapper<>();
        wrapper.eq("task_id", createOrderReq.getTaskId());
        OrderEntity existOrderEntity = orderMapper.selectOne(wrapper);
        if (ObjectUtil.isNotNull(existOrderEntity)) {
            throw new ToolManageException(ToolManageEx.ORDER_TASK_ID_REPEAT.getCode(), ToolManageEx.ORDER_TASK_ID_REPEAT.getMsg());
        }
        // 构造工单信息
        OrderEntity orderEntity = buildOrder(createOrderReq);
        //产品信息未录入
        ProductionEntity productionEntity = getProductionEntity(orderEntity.getFigureNo());
        buildOrderStatus(orderEntity, createOrderReq.getVersion(), productionEntity);
        orderEntity.setOrderStatus(0);
        orderMapper.insert(orderEntity);
        return Boolean.TRUE;
    }

    private ProductionEntity getProductionEntity(String figureNo) {
        LambdaQueryWrapper<ProductionEntity> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(ProductionEntity::getFigureNo, figureNo);
        return productionMapper.selectOne(wrapper);
    }


    public void buildOrderStatus(OrderEntity orderEntity, Integer version, ProductionEntity productionEntity) {
        if (ObjectUtil.isNull(productionEntity)) {
            //新建工单关联产品信息未录入
            orderEntity.setStatus(CommonConstant.ORDER_NEW);
            return;
        }
        //已关联产品
        //关联产品就拉取产品基础信息到工单
        orderEntity.setProductionName(productionEntity.getName());
        orderEntity.setProductionNum(productionEntity.getProductionNum());
        orderEntity.setMaterialNo(productionEntity.getMaterialNo());
        orderEntity.setFigureNoImage(productionEntity.getImage());
        orderEntity.setHeavy(productionEntity.getHeavy());
        if (productionEntity.getStatus().equals(CommonConstant.NEW_PRODUCTION)) {
            //关联产品未编辑完成
            orderEntity.setStatus(CommonConstant.ORDER_PRODUCTION_CONNECT_NOT_DONE);
            //产品已关联工艺
//            if (productionEntity.getProductionProcessConnectStatus().equals(CommonConstant.PRODUCTION_PROCESS_NOT_CONNECT)) {
//                //未关联工序直接返回不做快照拉取
//                return;
//            }
            return;
        }
        //工单编辑完成状态
        orderEntity.setStatus(CommonConstant.ORDER_PRODUCTION_CONNECT_DONE);
        buildOrderSnapShot(orderEntity, version);
    }

    public void buildOrderSnapShot(OrderEntity orderEntity, Integer version) {
        //拉取工单快照数据
        // 获取关联的物料和工艺工序
        ProcessEntity processEntity = getProcessEntity(orderEntity.getMaterialNo(), version);
        List<ProcessCraftEntity> processCraftEntityList = getProcessCraftEntityList(processEntity);
        List<ProductionBomEntity> productionBomEntityList = getProductionBomEntityList(orderEntity.getMaterialNo());
        OrderDo orderDo = new OrderDo(orderEntity, processCraftEntityList, productionBomEntityList);
        // 持久化快照
        persistOrder(orderDo);
    }

    private ProcessEntity getProcessEntity(String materialNo, Integer version) {
        String code = processRepository.selectCodeByFigureNo(materialNo);
        LambdaQueryWrapper<ProcessEntity> processWrapper = new LambdaQueryWrapper<>();
        processWrapper.eq(ProcessEntity::getCode, code).
                eq(ProcessEntity::getVersion, ObjectUtil.isNull(version) ? CommonConstant.INIT_VERSION : version);
        //AssertExUtil.assertNoNull(processEntity, ToolManageEx.PROCESS_CONNECTION_NO_EXIST);
        return processMapper.selectOne(processWrapper);
    }

    private List<ProductionBomEntity> getProductionBomEntityList(String figureNo) {
        LambdaQueryWrapper<ProductionBomEntity> productionBomWrapper = new LambdaQueryWrapper<>();
        productionBomWrapper.eq(ProductionBomEntity::getFigureNo, figureNo);
        return productionBomMapper.selectList(productionBomWrapper);
    }

    private List<ProcessCraftEntity> getProcessCraftEntityList(ProcessEntity processEntity) {
        LambdaQueryWrapper<ProcessCraftEntity> processCraftWrapper = new LambdaQueryWrapper<>();
        processCraftWrapper.eq(ProcessCraftEntity::getProcessCode, processEntity.getCode()).
                eq(ProcessCraftEntity::getVersion, processEntity.getVersion());
        return processCraftMapper.selectList(processCraftWrapper);
    }

    public void persistOrder(OrderDo orderDo) {
        OrderEntity orderEntity = orderDo.getOrderEntity();
        // 拷贝工单id到物料
        //orderDo.getOrderBomEntity().setOrderId(orderEntity.getId());
        orderDo.getOrderBomEntity().setTaskId(orderEntity.getTaskId());
        // 持久化物料
        if (ObjectUtil.isNotNull(orderDo.getOrderBomEntity())) {
            QueryWrapper<OrderBomEntity> bomEntityQueryWrapper = new QueryWrapper<>();
            bomEntityQueryWrapper.eq("task_id", orderDo.getOrderBomEntity().getTaskId());
            OrderBomEntity existBom = orderBomMapper.selectOne(bomEntityQueryWrapper);
            if (ObjectUtil.isNull(existBom)) {
                orderBomMapper.insert(orderDo.getOrderBomEntity());
            }
        }
        // 拷贝工单id到工艺
        //orderDo.getOrderCraftEntity().setOrderId(orderEntity.getId());
        orderDo.getOrderCraftEntity().setTaskId(orderEntity.getTaskId());
        if (ObjectUtil.isNotNull(orderDo.getOrderCraftEntity())) {
            QueryWrapper<OrderCraftEntity> orderCraftWrapper = new QueryWrapper<>();
            orderCraftWrapper.eq("task_id", orderDo.getOrderCraftEntity().getTaskId());
            OrderCraftEntity existCraft = orderCraftMapper.selectOne(orderCraftWrapper);
            if (ObjectUtil.isNull(existCraft)) {
                orderCraftMapper.insert(orderDo.getOrderCraftEntity());
            }
        }
        //持久化程序
//        List<OrderProgramEntity> orderProgramEntityList = buildOrderProgramList(orderDo.getProcessCraftEntityList(), orderEntity.getTaskId());
//        if (CollectionUtil.isNotEmpty(orderProgramEntityList)) {
//            orderProgramMapper.insertBatchSomeColumn(orderProgramEntityList);
//        }
    }

    public void persistOrderReload(OrderDo orderDo) {
        OrderEntity orderEntity = orderDo.getOrderEntity();
        // 拷贝工单id到物料
        orderDo.getOrderBomEntity().setTaskId(orderEntity.getTaskId());
        // 持久化物料
        orderBomMapper.insert(orderDo.getOrderBomEntity());
        // 拷贝工单id到工艺
        orderDo.getOrderCraftEntity().setTaskId(orderEntity.getTaskId());
        orderCraftMapper.insert(orderDo.getOrderCraftEntity());
    }

    private List<OrderProgramEntity> buildOrderProgramList(List<ProcessCraftEntity> processCraftEntityList, String taskId) {
        List<OrderProgramEntity> orderProgramEntityList = new ArrayList<>();
        if (CollectionUtil.isEmpty(processCraftEntityList)) {
            return orderProgramEntityList;
        }
        //构建工序关联程序快照信息
        List<ProcessCraftEntity> processCraftEntities = processCraftEntityList
                .stream()
                .filter(processCraftEntity -> !"".equals(processCraftEntity.getProgramCode()))
                .collect(Collectors.toList());
        List<Integer> equipmentIds = subProgramManageService.selectEquipmentIds();
        for (ProcessCraftEntity processCraftEntity : processCraftEntities) {
            for (int i = 0; i < equipmentIds.size(); i++) {
                List<SubProgramEntity> subProgramEntityList = subProgramRespository.findSubprogramByProgram(processCraftEntity.getProgramCode(), equipmentIds.get(i));
                ProgramEntity programEntity = programRepository.selectByProgramCode(processCraftEntity.getProgramCode());
                if (CollectionUtil.isEmpty(subProgramEntityList) || ObjectUtil.isNull(programEntity)) {
                    continue;
                }
                OrderProgramEntity orderProgramEntity = new OrderProgramEntity();
                orderProgramEntity.setProcessCraftName(processCraftEntity.getName());
                orderProgramEntity.setTaskId(taskId);
                //构建ProgramParamVo
                buildProgramParam(orderProgramEntity, processCraftEntity);
                orderProgramEntity.setSeq(processCraftEntity.getSeq());
                //构建SubProgramParamVo
                orderProgramEntity.setOrderSubProgramParam(JSONArray.toJSONString(new ArrayList<>()));
                orderProgramEntity.setEquipmentId(equipmentIds.get(i));
                orderProgramEntity.setEquipmentName(warehouseRespository.selectNameById(equipmentIds.get(i)));
                List<SubProgramParamVo> subProgramParamVoList = subProgramEntityList.stream().map(this::buildSubProgramParamVo).collect(Collectors.toList());
                orderProgramEntity.setOrderSubProgramParam(JSONArray.toJSONString(subProgramParamVoList));
                orderProgramEntityList.add(orderProgramEntity);
            }
        }
        return orderProgramEntityList;
    }

    private List<ProcessCraftProgramEntity> getConnectProgram(ProcessCraftEntity processCraftEntity) {
        QueryWrapper<ProcessCraftProgramEntity> wrapper = new QueryWrapper<>();
        wrapper.eq("process_craft_id", processCraftEntity.getId()).eq("is_using", 1);
        List<ProcessCraftProgramEntity> processCraftProgramEntities = processCraftProgramMapper.selectList(wrapper);
        return processCraftProgramEntities;
    }

    private void buildProgramParam(OrderProgramEntity orderProgramEntity, ProcessCraftEntity processCraftEntity) {
        QueryWrapper<ProgramEntity> wrapper = new QueryWrapper<>();
        wrapper.eq("code", processCraftEntity.getProgramCode());
        ProgramEntity programEntity = programMapper.selectOne(wrapper);
        //查询主程序编码不为空
        if (ObjectUtil.isNotNull(programEntity)) {
            ProgramParamVo programParamVo = new ProgramParamVo();
            BeanUtils.copyProperties(programEntity, programParamVo);
            orderProgramEntity.setOrderProgramParam(JSONObject.toJSONString(programParamVo));
        }
    }

    private SubProgramParamVo buildSubProgramParamVo(SubProgramEntity subProgramEntity) {
        SubProgramParamVo subProgramParamVo = new SubProgramParamVo();
        subProgramParamVo.setCode(subProgramEntity.getCode());
        subProgramParamVo.setName(subProgramEntity.getName());
        subProgramParamVo.setToolCode(subProgramEntity.getToolCode());
        subProgramParamVo.setShankModel(subProgramEntity.getShankModel());
        subProgramParamVo.setToolModel(subProgramEntity.getToolModel());
        subProgramParamVo.setSeq(subProgramEntity.getSeq());
        subProgramParamVo.setExtension(subProgramEntity.getExtension());
        subProgramParamVo.setRpm(subProgramEntity.getRpm());
        subProgramParamVo.setFeed(subProgramEntity.getFeed());
        return subProgramParamVo;
    }


    private OrderEntity buildOrder(CreateOrderReq createOrderReq) {
        OrderEntity orderEntity = new OrderEntity();
        orderEntity.setTaskId(createOrderReq.getTaskId());
        orderEntity.setFigureNo(createOrderReq.getFigureNo());
        orderEntity.setPriority(createOrderReq.getPriority());
        orderEntity.setProductionName(createOrderReq.getProductionName());
        orderEntity.setProductionNum(createOrderReq.getProductionNum());
        orderEntity.setMaterialNo(createOrderReq.getMaterialNo());
        orderEntity.setPlanNumber(createOrderReq.getPlanNumber());
        orderEntity.setRealNumber(createOrderReq.getRealNumber());
        orderEntity.setHeavy(createOrderReq.getHeavy());
        orderEntity.setStorageSpace(createOrderReq.getStorageSpace());
        orderEntity.setFinishTime(createOrderReq.getFinishTime());
        orderEntity.setVersion(CommonConstant.INIT_VERSION);
        orderEntity.setStatus(OrderStatusEnum.NEW_BUILD.getStatus());
        return orderEntity;
    }

    @Transactional
    public boolean importOrder(List<OrderImport> orderImportList) {
        if (CollectionUtil.isEmpty(orderImportList)) {
            return Boolean.TRUE;
        }
        List<OrderEntity> existOrderList = orderMapper.selectList(new QueryWrapper<>());
        List<OrderEntity> orderEntities = buildOrderEntity(orderImportList, existOrderList);
        if (CollectionUtil.isNotEmpty(orderEntities)) {
            orderMapper.insertBatchSomeColumn(orderEntities);
        }
        return Boolean.TRUE;
    }

    @Transactional
    public List<Map<String, String>> importOrderReload(List<OrderImport> orderImportList) {
        List<OrderEntity> existOrderList = orderMapper.selectList(new QueryWrapper<>());
        List<OrderEntity> orderEntities = buildOrderEntity(orderImportList, existOrderList);
        if (CollectionUtil.isNotEmpty(orderEntities)) {
            orderMapper.insertBatchSomeColumn(orderEntities);
        }
        return orderEntities
                .stream()
                .map(this::transferOrderMap)
                .filter(CollectionUtil::isNotEmpty)
                .collect(Collectors.toList());
    }

    private Map<String, String> transferOrderMap(OrderEntity orderEntity) {
        Map<String, String> retMap = new HashMap<>();
        retMap.put("taskId", orderEntity.getTaskId());
        retMap.put("materialNo", orderEntity.getMaterialNo());
        return retMap;
    }

    private List<OrderEntity> buildOrderEntity(List<OrderImport> orderImportList, List<OrderEntity> existOrderList) {
        Set<OrderEntity> orderEntities = new HashSet<>();
        List<String> existTaskIdList = new ArrayList<>();
        for (OrderEntity entity : existOrderList) {
            existTaskIdList.add(entity.getTaskId());
        }
        //导入工单根据工单号去重
        for (OrderImport orderImport : orderImportList) {
            OrderEntity orderEntity = new OrderEntity();
            BeanUtil.copyProperties(orderImport, orderEntity);
            //工单号不存在
            if (!existTaskIdList.contains(orderEntity.getTaskId())) {
                orderEntity.setFigureNo(productionRespository.selectFigureNoByProNum(orderEntity.getProductionNum()));
                orderEntity.setStatus(OrderStatusEnum.NEW_BUILD.getStatus());
                orderEntity.setVersion(CommonConstant.INIT_VERSION);
                //利用set集合去重
                orderEntities.add(orderEntity);
            }
        }
        List<OrderEntity> orderEntityList = new ArrayList<>(orderEntities);
        //设置工单状态以及是否需要拉取产品快照
        orderEntityList.forEach(orderEntity -> {
            ProductionEntity productionEntity = getProductionEntity(orderEntity.getFigureNo());
            //buildOrderStatus(orderEntity, CommonConstant.INIT_VERSION, productionEntity);
            //设置工单加工状态
            orderEntity.setOrderStatus(0);
        });
        return orderEntityList;
    }

    private List<OrderEntity> buildOrderEntityReload(List<OrderImport> orderImportList, List<OrderEntity> existOrderList) {
        Set<OrderEntity> orderEntities = new HashSet<>();
        List<String> existTaskIdList = new ArrayList<>();
        for (OrderEntity entity : existOrderList) {
            existTaskIdList.add(entity.getTaskId());
        }
        //导入工单根据工单号去重
        for (OrderImport orderImport : orderImportList) {
            OrderEntity orderEntity = new OrderEntity();
            BeanUtil.copyProperties(orderImport, orderEntity);
            //工单号不存在
            if (!existTaskIdList.contains(orderEntity.getTaskId())) {
                orderEntity.setFigureNo(productionRespository.selectFigureNoByProNum(orderEntity.getProductionNum()));
                orderEntity.setStatus(OrderStatusEnum.NEW_BUILD.getStatus());
                orderEntity.setVersion(CommonConstant.INIT_VERSION);
                //利用set集合去重
                orderEntities.add(orderEntity);
            }
        }
        List<OrderEntity> orderEntityList = new ArrayList<>(orderEntities);
        //设置工单状态以及是否需要拉取产品快照
        orderEntityList.forEach(orderEntity -> {
            ProductionEntity productionEntity = getProductionEntity(orderEntity.getFigureNo());
            buildOrderStatus(orderEntity, CommonConstant.INIT_VERSION, productionEntity);
            //设置工单加工状态
            orderEntity.setOrderStatus(0);
        });
        return orderEntityList;
    }

    /**
     * 删除工单
     *
     * @param ids ids
     * @return
     * @throws ToolManageException
     */
    @Transactional
    public Boolean deleteOrder(List<Integer> ids) throws ToolManageException {
        if (CollectionUtil.isEmpty(ids)) {
            throw new ToolManageException(ToolManageEx.ORDER_NO_EXIST.getCode(), ToolManageEx.ORDER_NO_EXIST.getMsg());
        }
        List<OrderEntity> orderEntities = orderMapper.selectBatchIds(ids);
        List<String> taskIdList = orderEntities.stream().map(OrderEntity::getTaskId).collect(Collectors.toList());
        orderMapper.deleteBatchIds(ids);
        LambdaQueryWrapper<OrderBomEntity> deleteBomWrapper = new LambdaQueryWrapper<>();
        deleteBomWrapper.in(OrderBomEntity::getTaskId, taskIdList);
        orderBomMapper.delete(deleteBomWrapper);
        LambdaQueryWrapper<OrderCraftEntity> deleteCraftWrapper = new LambdaQueryWrapper<>();
        deleteCraftWrapper.in(OrderCraftEntity::getTaskId, taskIdList);
        orderCraftMapper.delete(deleteCraftWrapper);
        LambdaQueryWrapper<OrderProgramEntity> deleteProgramWrapper = new LambdaQueryWrapper<>();
        deleteProgramWrapper.in(OrderProgramEntity::getTaskId, taskIdList);
        orderProgramMapper.delete(deleteProgramWrapper);
        //清除采集数据表中该工单关联的数据
        machineToolDataLogRepository.deleteByTaskIds(taskIdList);
        return Boolean.TRUE;
    }

    /**
     * 查询物料细节
     *
     * @param taskId taskId
     * @return
     * @throws ToolManageException
     */
    public List<BomParamVo> queryOrderBomDetail(String taskId) throws ToolManageException {
        if (ObjectUtil.isNull(taskId)) {
            throw new ToolManageException(ToolManageEx.ORDER_NO_EXIST.getCode(), ToolManageEx.ORDER_NO_EXIST.getMsg());
        }
        OrderBomEntity orderBomEntity = selectOrderBomOne(taskId);
        if (ObjectUtil.isNull(orderBomEntity)) {
            return new ArrayList<>();
        }
        return transferOrderBom(orderBomEntity);
    }

    private List<BomParamVo> transferOrderBom(OrderBomEntity orderBomEntity) {
        String bomParam = orderBomEntity.getBomParam();
        if (bomParam.equals("[]")) {
            return new ArrayList<>();
        }
        return JSONArray.parseArray(bomParam, BomParamVo.class).stream().
                sorted(Comparator.comparingInt(BomParamVo::getSeq)).
                collect(Collectors.toList());
    }

    /**
     * 查询工艺的细节
     *
     * @param taskId taskId
     * @return
     */
    public List<CraftParamVo> queryOrderCraftDetail(String taskId) throws ToolManageException {
        if (ObjectUtil.isNull(taskId)) {
            throw new ToolManageException(ToolManageEx.ORDER_NO_EXIST.getCode(), ToolManageEx.ORDER_NO_EXIST.getMsg());
        }
        OrderCraftEntity orderCraftEntity = selectOrderCraftOne(taskId);
        if (ObjectUtil.isNull(orderCraftEntity)) {
            return new ArrayList<>();
        }
        return transferOrderCraft(orderCraftEntity);
    }

    public List<CraftParamVo> queryOrderCraftDetailReload(String taskId) {
        OrderCraftEntity orderCraftEntity = selectOrderCraftOne(taskId);
        if (ObjectUtil.isNull(orderCraftEntity)) {
            return new ArrayList<>();
        }
        return transferOrderCraft(orderCraftEntity);
    }


    private List<CraftParamVo> transferOrderCraft(OrderCraftEntity orderCraftEntity) {
        String craftParam = orderCraftEntity.getCraftParam();
        if (craftParam.equals("[]")) {
            return new ArrayList<>();
        }
        return JSONArray.parseArray(craftParam, CraftParamVo.class).stream().
                sorted(Comparator.comparingInt(CraftParamVo::getSeq)).
                collect(Collectors.toList());
    }


    public Boolean editOrderCraftList(EditOrderCraftReq editOrderCraftReq) throws ToolManageException {
        QueryWrapper<OrderCraftEntity> wrapper = new QueryWrapper<>();
        wrapper.eq("task_id", editOrderCraftReq.getTaskId());
        OrderCraftEntity orderCraftEntity = orderCraftMapper.selectOne(wrapper);
        orderCraftEntity.setCraftParam(JSONObject.toJSONString(editOrderCraftReq.getBatchUpdateReq()));
        orderCraftMapper.updateById(orderCraftEntity);
        //修改工单分配任务的状态
        QueryWrapper<OrderEntity> wrapper2 = new QueryWrapper<>();
        wrapper2.eq("task_id", editOrderCraftReq.getTaskId());
        OrderEntity orderEntity = orderMapper.selectOne(wrapper2);
        Integer flag = 1;
        for (CraftParamVo craftParamVo : editOrderCraftReq.getBatchUpdateReq()) {
            flag = flag * craftParamVo.getStatus();
        }
        if (flag == 1) {
            orderEntity.setOrderStatus(2);
            orderEntity.setFinishTime(new Date());
            orderMapper.updateById(orderEntity);
        }
        return Boolean.TRUE;
    }


    private List<CraftParamVo> buildCraftParamVoList(List<SingleCraftUpdateReq> batchUpdateReq, OrderEntity orderEntity) {
        if (CollectionUtil.isEmpty(batchUpdateReq)) {
            return new ArrayList<>();
        }
        List<CraftParamVo> craftParamVos = new ArrayList<>();
        for (int i = 0; i < batchUpdateReq.size(); i++) {
            SingleCraftUpdateReq singleCraftUpdateReq = batchUpdateReq.get(i);
            CraftParamVo craftParamVo = new CraftParamVo();
            // 为空重新生成编码
            craftParamVo.setCode(StringUtils.isEmpty(singleCraftUpdateReq.getCode()) ? "craft-" + UUIDUtil.getUUID() : singleCraftUpdateReq.getCode());
            craftParamVo.setName(singleCraftUpdateReq.getName());
            craftParamVo.setContent(singleCraftUpdateReq.getContent());
            craftParamVo.setProgramCode(singleCraftUpdateReq.getProgramCode());
            craftParamVo.setVersion(orderEntity.getVersion());
            craftParamVo.setAdjustNumber(singleCraftUpdateReq.getAdjustNumber());
            craftParamVo.setUnitsNumber(singleCraftUpdateReq.getUnitsNumber());
            craftParamVo.setQualifiedNumber(singleCraftUpdateReq.getQualifiedNumber());
            craftParamVo.setRejectedNumber(singleCraftUpdateReq.getRejectedNumber());
            craftParamVo.setOperator(singleCraftUpdateReq.getOperator());
            craftParamVo.setOperateTime(singleCraftUpdateReq.getOperateTime());
            craftParamVo.setSeq(i + 1);
            craftParamVos.add(craftParamVo);
        }
        return craftParamVos;
    }

    /**
     * 编辑bom
     *
     * @param editOrderBomReq editOrderBomReq
     * @return
     * @throws ToolManageException
     */
    public Boolean editOrderBomList(EditOrderBomReq editOrderBomReq) throws ToolManageException {
        // 校验
        AssertExUtil.assertNoNull(editOrderBomReq.getOrderId(), ToolManageEx.ORDER_NO_EXIST);
        OrderEntity orderEntity = orderMapper.selectById(editOrderBomReq.getOrderId());
        AssertExUtil.assertNoNull(orderEntity, ToolManageEx.ORDER_NO_EXIST);
        OrderBomEntity orderBomEntity = selectOrderBomOne(orderEntity.getTaskId());
        List<BomParamVo> originList = JSONArray.parseArray(orderBomEntity.getBomParam(), BomParamVo.class);
        List<BomParamVo> updateList = buildBomParamVoList(editOrderBomReq.getBatchUpdateBomReq(), orderEntity);
        // 更新数据为空，清空数据
        OrderBomLogic orderBomLogic = new OrderBomLogic(originList, updateList);
        orderBomLogic.buildOrderBomDo();
        OrderBomDo orderBomDo = orderBomLogic.getOrderBomDo();
        // 持久化
        orderBomEntity.setBomParam(JSONArray.toJSONString(orderBomDo.getTotalElement()));
        orderBomMapper.updateById(orderBomEntity);
        return Boolean.TRUE;
    }


    private OrderBomEntity selectOrderBomOne(String taskId) {
        LambdaQueryWrapper<OrderBomEntity> bomWrapper = new LambdaQueryWrapper<>();
        bomWrapper.eq(OrderBomEntity::getTaskId, taskId);
        return orderBomMapper.selectOne(bomWrapper);
    }

    private OrderCraftEntity selectOrderCraftOne(String taskId) {
        LambdaQueryWrapper<OrderCraftEntity> craftWrapper = new LambdaQueryWrapper<>();
        craftWrapper.eq(OrderCraftEntity::getTaskId, taskId);
        return orderCraftMapper.selectOne(craftWrapper);
    }

    private List<BomParamVo> buildBomParamVoList(List<SingleBomUpdateReq> batchUpdateReq, OrderEntity orderEntity) {
        if (CollectionUtil.isEmpty(batchUpdateReq)) {
            return new ArrayList<>();
        }
        List<BomParamVo> bomParamVos = new ArrayList<>();
        for (int i = 0; i < batchUpdateReq.size(); i++) {
            SingleBomUpdateReq singleBomUpdateReq = batchUpdateReq.get(i);
            BomParamVo bomParamVo = new BomParamVo();
            // 为空重新生成编码
            bomParamVo.setCode(StringUtils.isEmpty(singleBomUpdateReq.getCode()) ? "bom-" + UUIDUtil.getUUID() : singleBomUpdateReq.getCode());
            bomParamVo.setName(singleBomUpdateReq.getName());
            bomParamVo.setDescription(singleBomUpdateReq.getDescription());
            bomParamVo.setLocation(singleBomUpdateReq.getLocation());
            bomParamVo.setRealNum(singleBomUpdateReq.getRealNum());
            bomParamVo.setRequiredNum(singleBomUpdateReq.getRequiredNum());
            bomParamVo.setVersion(orderEntity.getVersion());
            bomParamVo.setOwner(singleBomUpdateReq.getOwner());
            bomParamVo.setUnit(singleBomUpdateReq.getUnit());
            bomParamVo.setSeq(i + 1);
            bomParamVos.add(bomParamVo);
        }
        return bomParamVos;
    }


    /**
     * 导出工单详情
     *
     * @param orderId orderId
     */
    public void exportOrderDetail(HttpServletResponse response, Integer orderId) {
        String outputFileName = orderId + "工单详情.xlsx";
        OrderExport orderExport = buildOrderExport(orderId);
        try {
            //InputStream templateStream = getClass().getResourceAsStream(CommonConstant.ORDER_TEMPLATE_PATH);
            InputStream templateStream = new ClassPathResource(CommonConstant.ORDER_TEMPLATE_PATH).getInputStream();
            ExcelWriter excelWriter = EasyExcel.write(response.getOutputStream()).autoCloseStream(Boolean.FALSE).withTemplate(templateStream).build();
            WriteSheet writeSheet = EasyExcel.writerSheet("sheet1").build();
            FillConfig fillConfig = FillConfig.builder().forceNewRow(Boolean.TRUE).build();
            excelWriter.fill(orderExport.getOrderDetailExport(), writeSheet);
            excelWriter.fill(new FillWrapper("bom", orderExport.getOrderBomExports()), writeSheet);
            excelWriter.fill(new FillWrapper("craft", orderExport.getOrderCraftExports()), fillConfig, writeSheet);
            // 下载刷新流
            EasyExcelUtil.downloadExcel(response, outputFileName);
        } catch (IOException e) {
            log.error("export order detail failed=====>", e);
        }
    }


    private OrderExport buildOrderExport(Integer orderId) {
        // 获取原始数据数据
        OrderEntity orderEntity = orderMapper.selectById(orderId);
        OrderBomEntity orderBomEntity = selectOrderBomOne(orderEntity.getTaskId());
        OrderCraftEntity orderCraftEntity = selectOrderCraftOne(orderEntity.getTaskId());
        OrderExport orderExport = new OrderExport();
        OrderDetailExport orderDetailExport = new OrderDetailExport();
        List<OrderBomExport> bomExportList = new ArrayList<>();
        ArrayList<OrderCraftExport> craftExportList = new ArrayList<>();

        // 填充数据
        BeanUtil.copyProperties(orderEntity, orderDetailExport);
        String bomParam = orderBomEntity.getBomParam();
        List<BomParamVo> bomParamVos = JSONArray.parseArray(bomParam, BomParamVo.class);
        for (BomParamVo bomParamVo : bomParamVos) {
            OrderBomExport orderBomExport = new OrderBomExport();
            BeanUtil.copyProperties(bomParamVo, orderBomExport);
            bomExportList.add(orderBomExport);
        }
        List<CraftParamVo> craftParamVos = JSONArray.parseArray(orderCraftEntity.getCraftParam(), CraftParamVo.class);
        for (CraftParamVo craftParamVo : craftParamVos) {
            OrderCraftExport orderCraftExport = new OrderCraftExport();
            BeanUtil.copyProperties(craftParamVo, orderCraftExport);
            craftExportList.add(orderCraftExport);
        }
        orderExport.setOrderDetailExport(orderDetailExport);
        orderExport.setOrderBomExports(bomExportList);
        orderExport.setOrderCraftExports(craftExportList);
        return orderExport;
    }

    public Map<String, Object> checkProgramKanBan(String taskId, String code, Integer equipmentId) {
        Map<String, Object> retMap = new HashMap<>();
        QueryWrapper<ProcessCraftEntity> wrapper = new QueryWrapper<>();
        wrapper.eq("code", code);
        ProcessCraftEntity existCraft = processCraftMapper.selectOne(wrapper);
        if (ObjectUtil.isNull(existCraft) || StringUtil.isEmpty(existCraft.getProgramCode())) {
            retMap.put("program", new ProgramEntity());
            retMap.put("subProgram", new ArrayList<>());
            return retMap;
        }

        //主程序
        String programCode = existCraft.getProgramCode();
        QueryWrapper<ProgramEntity> programWrapper = new QueryWrapper<>();
        programWrapper.eq("code", programCode);
        ProgramEntity programEntity = programMapper.selectOne(programWrapper);
        retMap.put("program", programEntity);

        //子程序
        QueryWrapper<EquipmentSubprogramMappingEntity> mappingWrapper = new QueryWrapper<>();
        mappingWrapper.eq("program_code", programEntity.getCode());
        mappingWrapper.eq("equipment_id", equipmentId);
        EquipmentSubprogramMappingEntity equipmentSubprogramMappingEntity = equipmentSubprogramMappingMapper.selectOne(mappingWrapper);
        if (ObjectUtil.isNull(equipmentSubprogramMappingEntity)) {
            retMap.put("subProgram", new ArrayList<>());
            return retMap;
        }
        List<SubProgramEntity> subProgramEntityList = subProgramRespository.selectListByProgramCode(equipmentSubprogramMappingEntity.getProgramCode());
        retMap.put("subProgram", subProgramEntityList);
        return retMap;
    }

    private ProgramKanBanReq buildProgramKanVos(String taskId, Integer seq, Integer equipmentId) {
        ProgramKanBanReq programKanBanReq = new ProgramKanBanReq();
        OrderProgramEntity orderProgramEntity = orderProgramRepository.selectUnique(taskId, seq, equipmentId);
        if (ObjectUtil.isNull(orderProgramEntity)) {
            return programKanBanReq;
        }
        String programParam = orderProgramEntity.getOrderProgramParam();
        ProgramEntity o = JSONObject.parseObject(programParam, ProgramEntity.class);

        String subProgramParam = orderProgramEntity.getOrderSubProgramParam();
        List<SubProgramEntity> subProgramEntityList = JSONObject.parseArray(subProgramParam, SubProgramEntity.class);

        programKanBanReq.setProgram(o);
        programKanBanReq.setSubProgramEntities(subProgramEntityList);
        return programKanBanReq;
    }

    public void exportOrder(HttpServletResponse response) throws IOException {
        //设置excel文件的mime类型
        response.setContentType("application/vnd.openxmlformats-officedocument.spreadsheetml.sheet");
        response.setCharacterEncoding("utf-8");
        String fileName = URLEncoder.encode("工单导入模板样式", "UTF-8").replaceAll("\\+", "%20");
        response.setHeader("Content-disposition", "attachment;filename*=utf-8''" + fileName + ".xlsx");
        //主标题和副标题在excel中分别是是第0和第1行
        List<Integer> columnIndexes = Arrays.asList(0, 1);
        //自定义标题和内容策略(具体定义在下文)
        CellStyleStrategy cellStyleStrategy =
                new CellStyleStrategy(columnIndexes, new WriteCellStyle(), new WriteCellStyle());
        ExcelWriter excelWriter = EasyExcel.write(response.getOutputStream())
                .registerWriteHandler(new CellRowHeightStyleStrategy())   //设置行高的策略
                .registerWriteHandler(cellStyleStrategy)        //设置表头和内容的策略
                .build();
        writeData(excelWriter);
        excelWriter.finish();
    }

    /**
     * 写入数据
     *
     * @param excelWriter excelWriter
     */
    private void writeData(ExcelWriter excelWriter) {
        WriteSheet writeSheet = new WriteSheet();
        //设置写到第几个sheet
        writeSheet.setSheetNo(0);
        writeSheet.setSheetName("生产订单导入模板");
        //设置表头
        List<List<String>> headList = new ArrayList<>();
        String orderName = "生产订单";
        String planName = "计划信息";
        headList.add(Arrays.asList(orderName, "生产订单"));
        headList.add(Arrays.asList(orderName, "物料编码"));
        headList.add(Arrays.asList(orderName, "物料型号"));
        headList.add(Arrays.asList(planName, "物料名称"));
        headList.add(Arrays.asList(planName, "计划数量"));
        headList.add(Arrays.asList(planName, "创建日期"));
        headList.add(Arrays.asList(planName, "交货日期"));
        headList.add(Arrays.asList(planName, "优先级"));
        headList.add(Arrays.asList(planName, "备注"));
        writeSheet.setHead(headList);
        //（设置数据）
        //第一列序号从1开始增加
        ArrayList<Object> dataList = new ArrayList<>();
        excelWriter.write(dataList, writeSheet);
    }

    public Object selectCraftTaskChild(String taskId, Integer seq) {
        List<OrderTaskChildVo> orderTaskChildVos = machineToolTaskRespository.selectChildListByTaskIdAndSeq(taskId, seq);
        if (CollectionUtil.isNotEmpty(orderTaskChildVos)) {
            orderTaskChildVos.forEach(orderTaskChildVo -> {
                if (orderTaskChildVo.getHandleTime().equals(new BigDecimal("0.00"))) {
                    return;
                }
                orderTaskChildVo.setSingleTimeConsuming(orderTaskChildVo.getHandleTime().divide(new BigDecimal(orderTaskChildVo.getNumber())));
            });
        }
        return orderTaskChildVos;
    }

    public void CompleteTheTask(String taskId, Integer seq) {
        Date date = new Date();
        machineToolTaskRespository.updataIsdone(taskId, seq, date);
    }

    public PageResult<OrderEntity> lackOrderProgram(QueryOrderReq queryOrderReq) {
        List<OrderEntity> list = queryOrderListReload(queryOrderReq);
        List<OrderEntity> pageList = new ArrayList<>();
        if (CollectionUtil.isNotEmpty(list)) {
            //过滤掉编辑完成状态的工单
            list = list.stream().filter(orderEntity -> 1 == orderEntity.getStatus()).collect(Collectors.toList());
            if (CollectionUtil.isNotEmpty(list)) {
                Iterator<OrderEntity> iterator = list.iterator();
                while (iterator.hasNext()) {
                    OrderEntity orderEntity = iterator.next();
                    if (StringUtil.isNotEmpty(orderEntity.getFigureNo())) {
                        QueryWrapper<ProductionEntity> wrapper = new QueryWrapper<>();
                        wrapper.eq("figure_no", orderEntity.getFigureNo());
                        ProductionEntity productionEntity = productionMapper.selectOne(wrapper);
                        if (ObjectUtil.isNotNull(productionEntity)
                                && productionEntity.getProductionProcessConnectStatus() == 1
                                && productionEntity.getProcessStatus() == 1) {
                            iterator.remove();
                        }
                    }
                }
            }
        }
        //手动分页
        if (CollectionUtil.isNotEmpty(list)) {
            pageList = CommonUtil.pageList(list, queryOrderReq.getPageNum(), queryOrderReq.getPageSize());
        }
        return new PageResult<>(pageList, (long) list.size());

    }

    public List<OrderEntity> lackOrderProgramReload(QueryOrderReq queryOrderReq) {
        List<OrderEntity> list = queryOrderListReload(queryOrderReq);
        List<OrderEntity> pageList = new ArrayList<>();
        if (CollectionUtil.isNotEmpty(list)) {
            //过滤掉编辑完成状态的工单
            list = list.stream().filter(orderEntity -> 1 == orderEntity.getStatus()).collect(Collectors.toList());
            if (CollectionUtil.isNotEmpty(list)) {
                Iterator<OrderEntity> iterator = list.iterator();
                while (iterator.hasNext()) {
                    OrderEntity orderEntity = iterator.next();
                    if (StringUtil.isNotEmpty(orderEntity.getFigureNo())) {
                        QueryWrapper<ProductionEntity> wrapper = new QueryWrapper<>();
                        wrapper.eq("figure_no", orderEntity.getFigureNo());
                        ProductionEntity productionEntity = productionMapper.selectOne(wrapper);
                        if (ObjectUtil.isNotNull(productionEntity)
                                && productionEntity.getProductionProcessConnectStatus() == 1
                                && productionEntity.getProcessStatus() == 1) {
                            iterator.remove();
                        }
                    }
                }
            }
        }
        return list;

    }


    public Object queryOrderTaskId(String taskId) {
        List<String> taskIds = orderRespository.selectByTaskId(taskId);
        return CollectionUtil.isNotEmpty(taskIds) ? taskIds : new ArrayList<>();
    }

    public List<Map<String, String>> abutmentOrder(AbutmentOrderReq abutmentOrderReq) {
        List<AbutmentOrderEntity> abutmentOrders = querySqlServerService.abutmentOrder(abutmentOrderReq);
        if (CollectionUtil.isNotEmpty(abutmentOrders)) {
            return abutmentOrderList(abutmentOrders);
        }
        return new ArrayList<>();
    }

    @Transactional
    public void deleteData(List<AbutmentOrderEntity> abutmentOrderEntities) {
        if(CollectionUtil.isNotEmpty(abutmentOrderEntities)){
            abutmentOrderEntities.forEach(abutmentOrder ->{
                //删除工单信息
                QueryWrapper<OrderEntity> orderWrapper = new QueryWrapper<>();
                orderWrapper.eq("task_id" , abutmentOrder.getTaskId());
                orderMapper.delete(orderWrapper);
                //删除bom快照
                QueryWrapper<OrderBomEntity> orderBomWrapper = new QueryWrapper<>();
                orderBomWrapper.eq("task_id" , abutmentOrder.getTaskId());
                orderBomMapper.delete(orderBomWrapper);
                //删除craft快照
                QueryWrapper<OrderCraftEntity> orderCraftWrapper = new QueryWrapper<>();
                orderCraftWrapper.eq("task_id" , abutmentOrder.getTaskId());
                orderCraftMapper.delete(orderCraftWrapper);
                //删除产品
                QueryWrapper<ProductionEntity> productionWrapper = new QueryWrapper<>();
                productionWrapper.eq("material_no" , abutmentOrder.getMaterialNo());
                ProductionEntity productionEntity = productionMapper.selectOne(productionWrapper);
                if(ObjectUtil.isNotNull(productionEntity)){
                    //删除bom
                    QueryWrapper<ProductionBomEntity> productionBomWrapper = new QueryWrapper<>();
                    productionBomWrapper.eq("figure_no" , productionEntity.getMaterialNo());
                    productionBomMapper.delete(productionBomWrapper);
                    //删除产品和工艺关联关系
                    QueryWrapper<ProductionProcessEntity> productionProcessWrapper = new QueryWrapper<>();
                    productionProcessWrapper.eq("production_id" , productionEntity.getMaterialNo());
                    productionProcessMapper.delete(productionProcessWrapper);
                    //删除工艺
                    QueryWrapper<ProcessEntity> processWrapper = new QueryWrapper<>();
                    processWrapper.eq("process_num" , productionEntity.getMaterialNo());
                    ProcessEntity processEntity = processMapper.selectOne(processWrapper);
                    processMapper.delete(processWrapper);
                    if(ObjectUtil.isNotNull(processEntity)){
                        //删除工艺工序
                        QueryWrapper<ProcessCraftEntity> processCraftWrapper = new QueryWrapper<>();
                        processCraftWrapper.eq("process_code" , processEntity.getCode());
                        processCraftMapper.delete(processCraftWrapper);
                    }
                    //删除程序看板
                    QueryWrapper<ProgramEntity> programWrapper = new QueryWrapper<>();
                    programWrapper.eq("program_num" , productionEntity.getMaterialNo());
                    ProgramEntity programEntity = programMapper.selectOne(programWrapper);
                    programMapper.delete(programWrapper);
                    if(ObjectUtil.isNotNull(programEntity)){
                        //删除对应的子程序
                        QueryWrapper<SubProgramEntity> subProgramWrapper = new QueryWrapper<>();
                        subProgramWrapper.eq("program_code" , programEntity.getCode());
                        subProgramMapper.delete(subProgramWrapper);
                        //删除对应的子程序印射表
                        QueryWrapper<EquipmentSubprogramMappingEntity> mappingWrapper = new QueryWrapper<>();
                        mappingWrapper.eq("program_code" , programEntity.getCode());
                        mappingMapper.delete(mappingWrapper);
                    }
                }
                productionMapper.delete(productionWrapper);
            });
        }


    }

    private List<Map<String, String>> abutmentOrderList(List<AbutmentOrderEntity> abutmentOrders) {
        List<OrderImport> orderEntities = new ArrayList<>();
        abutmentOrders.forEach(abutmentOrder -> {
            OrderImport orderImport = new OrderImport();
            if (ObjectUtil.isNotNull(abutmentOrder.getPriority())) {
                if (abutmentOrder.getPriority().contains("c")) {
                    orderImport.setSortPriority(3);
                } else if (abutmentOrder.getPriority().contains("?")) {
                    orderImport.setSortPriority(2);
                } else if (abutmentOrder.getPriority().contains("1")) {
                    orderImport.setSortPriority(1);
                }
            }
            BeanUtil.copyProperties(abutmentOrder, orderImport);
            orderEntities.add(orderImport);
        });
        return importOrderReload(orderEntities);
    }

    public List<Map<String, String>> abutmentOrder(List<String> taskIds) {
        List<AbutmentOrderEntity> abutmentOrders = querySqlServerService.abutmentOrder(taskIds);
        if (CollectionUtil.isNotEmpty(abutmentOrders)) {
            return abutmentOrderList(abutmentOrders);
        }
        return new ArrayList<>();
    }

    public Object allotedLackOrderProgram(QryOrderReq qryOrderReq) {
        List<OrderEntity> lackProgramOrders = queryOrderListReload(qryOrderReq);
        //根据分配任务的工单过滤
        List<String> taskIds = machineToolTaskRespository.selectGroupTaskId(qryOrderReq.getEquipmentIds());
        if (CollectionUtil.isNotEmpty(lackProgramOrders) && CollectionUtil.isNotEmpty(taskIds)) {
            List<OrderEntity> pageList = new ArrayList<>();
            lackProgramOrders = lackProgramOrders.stream().filter(orderEntity -> taskIds.contains(orderEntity.getTaskId())).collect(Collectors.toList());
            if (CollectionUtil.isNotEmpty(lackProgramOrders)) {
                pageList = CommonUtil.pageList(lackProgramOrders, qryOrderReq.getPageNum(), qryOrderReq.getPageSize());
            }
            return new PageResult<>(pageList, (long) lackProgramOrders.size());
        }
        return new PageResult<>(new ArrayList<>(), (long) 0);
    }

    public Object orderCraft(QueryOrderReloadReq queryOrderReloadReq) throws ToolManageException {
        List<CraftParamVo> resList = new ArrayList<>();
        List<OrderCraftVo> resultList = new ArrayList<>();
        List<OrderEntity> orderEntities = queryOrderListReload(queryOrderReloadReq);
        if(CollectionUtil.isNotEmpty(queryOrderReloadReq.getMaterialNos())){
            orderEntities = orderEntities
                    .stream()
                    .filter(orderEntity -> {
                if(StringUtils.isNotBlank(orderEntity.getMaterialNo())){
                    for (String materialNo : queryOrderReloadReq.getMaterialNos()) {
                        if (orderEntity.getMaterialNo().contains(materialNo)) {
                            return true;
                        }
                    }
                }
                return false;
            }).collect(Collectors.toList());
        }
        if (CollectionUtil.isNotEmpty(orderEntities)) {
            for (OrderEntity orderEntity : orderEntities) {
                List<CraftParamVo> craftParamVos = queryOrderCraftDetail(orderEntity.getTaskId());
                if (CollectionUtil.isNotEmpty(craftParamVos)) {
                    for (int i = 0; i < craftParamVos.size(); i++) {
                        CraftParamVo craftParamVo = craftParamVos.get(i);
                        OrderCraftVo orderCraftVo = new OrderCraftVo();
                        orderCraftVo.setPriority(orderEntity.getPriority());
                        orderCraftVo.setProductionNum(orderEntity.getProductionNum());
                        orderCraftVo.setTaskId(orderEntity.getTaskId());
                        orderCraftVo.setFinishTime(orderEntity.getFinishTime());
                        orderCraftVo.setProductionName(orderEntity.getProductionName());
                        orderCraftVo.setMaterialNo(orderEntity.getMaterialNo());
                        BeanUtils.copyProperties(craftParamVo, orderCraftVo);
                        if (StringUtil.isNotEmpty(queryOrderReloadReq.getCraftName())
                                && !orderCraftVo.getName().contains(queryOrderReloadReq.getCraftName())) {
                            continue;
                        }

                        if (ObjectUtil.isNotNull(queryOrderReloadReq.getFlag()) && queryOrderReloadReq.getFlag() && i != 0) {
                            //根据前序工序未已完成状态过滤
                            CraftParamVo preCraftParamVo = craftParamVos.get(i - 1);
                            if (ObjectUtil.isNotNull(craftParamVo.getStatus())) {
                                if (craftParamVo.getStatus() == 9 || preCraftParamVo.getStatus() != 9) {
                                    continue;
                                }
                            }
                        }
                        if (StringUtil.isNotEmpty(orderCraftVo.getTaskId())) {
                            List<CraftParamVo> craftParamVos1 = queryOrderCraftDetail(orderCraftVo.getTaskId());
                            //resList.addAll(craftParamVos1);
                            orderCraftVo.setCraftParamVos(craftParamVos1);
                        }
                        //过滤在制工序
                        if(ObjectUtil.isNotNull(queryOrderReloadReq.getFlag1())&& queryOrderReloadReq.getFlag1() && ObjectUtil.isNotNull(orderCraftVo)){
                            if(ObjectUtil.isNotNull(orderCraftVo.getStatus()) && orderCraftVo.getStatus() == 5){
                                resultList.add(orderCraftVo);
                            }
                            //craftParamVos1 = craftParamVos1.stream().filter(craftParamVo1 -> ObjectUtil.isNotNull(craftParamVo1.getStatus()) && craftParamVo1.getStatus() == 5).collect(Collectors.toList());
                        }else{
                            resultList.add(orderCraftVo);
                        }
                    }
                }
            }
        }
        //根据planTime模糊查询
        if (StringUtil.isNotEmpty(queryOrderReloadReq.getPlanTime())) {
            resultList = resultList.stream().filter(orderCraftVo -> ObjectUtil.isNotNull(orderCraftVo.getPlanTime()) && orderCraftVo.getPlanTime().contains(queryOrderReloadReq.getPlanTime())).collect(Collectors.toList());
        }
        //根据planTime排序
        if (ObjectUtil.isNotNull(queryOrderReloadReq.getSortFlag())) {
            if (queryOrderReloadReq.getSortFlag()) {
                //正序
                resultList = resultList.stream().sorted(Comparator.comparing(CraftParamVo::getPlanTime, Comparator.nullsLast(String::compareTo))).collect(Collectors.toList());
            } else {
                //倒序
                resultList = resultList.stream().sorted(Comparator.comparing(CraftParamVo::getPlanTime, Comparator.nullsFirst(String::compareTo)).reversed()).collect(Collectors.toList());
            }
        }
        //搜索可分配数量不为0的
        if (ObjectUtil.isNotNull(queryOrderReloadReq.getCraftUnallocatedNumber()) && CollectionUtil.isNotEmpty(resultList)) {
            resultList = resultList
                    .stream()
                    .filter(orderCraftVo -> ObjectUtil.isNotNull(orderCraftVo.getCraftUnallocatedNumber()) && Objects.equals(orderCraftVo.getCraftUnallocatedNumber(), queryOrderReloadReq.getCraftUnallocatedNumber()))
                    .collect(Collectors.toList());
        }
        //搜索未分配的
        if (ObjectUtil.isNotNull(queryOrderReloadReq.getTypeFlag()) && CollectionUtil.isNotEmpty(resultList)) {
            resultList = resultList
                    .stream()
                    .filter(orderCraftVo -> ObjectUtil.isNotNull(orderCraftVo.getTypeFlag()) && Objects.equals(orderCraftVo.getTypeFlag(), queryOrderReloadReq.getTypeFlag()))
                    .collect(Collectors.toList());
        }
        List<OrderCraftVo> pageList = new ArrayList<>();
        if (CollectionUtil.isNotEmpty(resultList)) {
            //手动分页
            pageList = CommonUtil.pageList(resultList, queryOrderReloadReq.getPageNum(), queryOrderReloadReq.getPageSize());
            if (CollectionUtil.isNotEmpty(pageList)) {
                pageList.forEach(orderCraftVo -> orderCraftVo.setMachineToolNames(shareFileService.queryMachineToolProgramGroupReload(orderCraftVo.getMaterialNo().trim())));
            }
        }
        return new PageResult<>(pageList, (long) resultList.size());
    }

    public Object abutmentOrderStatus(List<String> taskIds) {
        //查询所有工单号去更新
        List<String> allTaskIds = getAllTaskIds();
        if(CollectionUtil.isEmpty(taskIds)){
            return Boolean.TRUE;
        }
        List<List<String>> lists = CommonUtil.groupList(allTaskIds);
        List<AbutmentOrderCraftEntity> abutmentOrderCraftEntities = new ArrayList<>();
        for (List<String> list : lists) {
            abutmentOrderCraftEntities.addAll(querySqlServerService.queryAbutmentOrderCraft(list));
        }
        //List<AbutmentOrderCraftEntity> abutmentOrderCraftEntities = querySqlServerService.queryAbutmentOrderCraft(taskIds);
        List<OrderEntity> updateOrderEntities = new ArrayList<>();
        List<OrderCraftEntity> updateOrderCraftEntities = new ArrayList<>();
        List<MachineToolTaskEntity> updateTaskList = new ArrayList<>();
        List<String> materialNos = new ArrayList<>();
        if (CollectionUtil.isNotEmpty(abutmentOrderCraftEntities)) {
            List<String> abutmentTaskIds = abutmentOrderCraftEntities.stream().map(AbutmentOrderCraftEntity::getTaskId).collect(Collectors.toList());
            QueryWrapper<OrderEntity> orderWrapper = new QueryWrapper<>();
            orderWrapper.in("task_id", abutmentTaskIds);
            List<OrderEntity> orderEntities = orderMapper.selectList(orderWrapper);
            Map<String , OrderEntity> taskIdOrderEntityMap = orderEntities.stream().collect(Collectors.toMap(OrderEntity::getTaskId , OrderEntity->OrderEntity));

            QueryWrapper<OrderCraftEntity> orderCraftWrapper = new QueryWrapper<>();
            orderCraftWrapper.in("task_id", abutmentTaskIds);
            List<OrderCraftEntity> existOrderCraft = orderCraftMapper.selectList(orderCraftWrapper);
            Map<String , OrderCraftEntity> taskIdOrderCraftEntityMap = new HashMap<>();
            if(CollectionUtil.isNotEmpty(existOrderCraft)){
                taskIdOrderCraftEntityMap = existOrderCraft.stream().collect(Collectors.toMap(OrderCraftEntity::getTaskId , OrderCraftEntity->OrderCraftEntity));
            }

            QueryWrapper<MachineToolTaskEntity> taskWrapper = new QueryWrapper<>();
            taskWrapper.in("order_task_id" , abutmentTaskIds);
            List<MachineToolTaskEntity> machineToolTaskEntities = machineToolTaskMapper.selectList(taskWrapper);
            Map<String , List<MachineToolTaskEntity>> groupByTaskIdMap = new HashMap<>();
            if(CollectionUtil.isNotEmpty(machineToolTaskEntities)){
                groupByTaskIdMap = machineToolTaskEntities.stream().collect(Collectors.groupingBy(MachineToolTaskEntity::getOrderTaskId));
            }

            Map<String , List<ProductionBomEntity>> productionEntityMap = new HashMap<>();
            QueryWrapper<ProductionBomEntity> wrapper = new QueryWrapper<>();
            wrapper.in("figure_no" , orderEntities.stream().map(OrderEntity::getMaterialNo).collect(Collectors.toList()));
            List<ProductionBomEntity> existProductions = productionBomMapper.selectList(wrapper);
            if(CollectionUtil.isNotEmpty(existProductions)){
                productionEntityMap = existProductions.stream().collect(Collectors.groupingBy(ProductionBomEntity::getFigureNo));
            }
            for (AbutmentOrderCraftEntity abutmentOrderCraftEntity : abutmentOrderCraftEntities) {
                //更新对应工单状态
                OrderEntity orderEntity = taskIdOrderEntityMap.get(abutmentOrderCraftEntity.getTaskId());
                if(ObjectUtil.isNotNull(orderEntity) && !Objects.equals(orderEntity.getAbutmentStatus() , abutmentOrderCraftEntity.getAbutmentStatus())){
                    orderEntity.setAbutmentStatus(abutmentOrderCraftEntity.getAbutmentStatus());
                    updateOrderEntities.add(orderEntity);
                }
                //addMaterialNos(materialNos, orderEntity.getMaterialNo());
                addMaterialNosReload(materialNos , productionEntityMap, orderEntity.getMaterialNo());
                //更新对应工序状态
                List<AbutmentProcessCraftEntity> abutmentProcessCraftEntityList = abutmentOrderCraftEntity.getAbutmentProcessCraftEntityList();

                OrderCraftEntity orderCraft = taskIdOrderCraftEntityMap.get(abutmentOrderCraftEntity.getTaskId());
                if (ObjectUtil.isNotNull(orderCraft) && ObjectUtil.isNotNull(orderCraft.getId()) && CollectionUtil.isNotEmpty(abutmentProcessCraftEntityList)) {
                    List<CraftParamVo> craftParamVos = transferOrderCraft(orderCraft);
                    if (CollectionUtil.isNotEmpty(craftParamVos)) {
                        for (CraftParamVo craftParamVo : craftParamVos) {
                            if(Objects.equals(craftParamVo.getStatus() , 9)){
                                continue;
                            }
                            for (AbutmentProcessCraftEntity abutmentProcessCraftEntity : abutmentProcessCraftEntityList) {
                                if (Objects.equals(craftParamVo.getSeq(), abutmentProcessCraftEntity.getSeq())) {
                                    craftParamVo.setStartTime(abutmentProcessCraftEntity.getStartTime());
                                    craftParamVo.setStatus(abutmentProcessCraftEntity.getProcessesStatus());
                                    craftParamVo.setEndTime(abutmentProcessCraftEntity.getEndTime());
                                    craftParamVo.setInProcessNumber(abutmentProcessCraftEntity.getInProcessNumber());
                                    craftParamVo.setQualifiedNumber(abutmentProcessCraftEntity.getQualifiedNumber());
                                    craftParamVo.setInboundNumber(abutmentProcessCraftEntity.getInboundNumber());
                                    craftParamVo.setRejectedNumber(abutmentProcessCraftEntity.getRejectedNumber());
                                    //工序完成设置对应分配任务全部结束
                                    if (abutmentProcessCraftEntity.getProcessesStatus() == 9 || abutmentOrderCraftEntity.getAbutmentStatus() == 9) {
                                        //machineToolTaskRespository.updataIsdone(orderCraft.getTaskId(), craftParamVo.getSeq(), new Date());
                                        List<MachineToolTaskEntity> updateList = groupByTaskIdMap.get(abutmentOrderCraftEntity.getTaskId());
                                        if(CollectionUtil.isNotEmpty(updateList)){
                                            for (MachineToolTaskEntity machineToolTaskEntity : updateList) {
                                                if(Objects.equals(machineToolTaskEntity.getOrderSnapshotCraftSeq(), craftParamVo.getSeq())){
                                                    machineToolTaskEntity.setIsDone(1);
                                                    machineToolTaskEntity.setActualEndTime(new Date());
                                                    updateTaskList.add(machineToolTaskEntity);
                                                }
                                            }
                                        }
                                    }
                                }
                            }
                        }
                    }
                    orderCraft.setCraftParam(JSONArray.toJSONString(craftParamVos));
                    updateOrderCraftEntities.add(orderCraft);
                }
            }
        }
        if (CollectionUtil.isNotEmpty(updateOrderEntities)) {
            if(updateOrderEntities.size()>2000){
                List<List<OrderEntity>> updateOrderLists = CommonUtil.groupList(updateOrderEntities);
                updateOrderLists.forEach(updateOrderList -> orderMapper.updateBatchById(updateOrderList));
            }else{
                orderMapper.updateBatchById(updateOrderEntities);
            }
        }
        if (CollectionUtil.isNotEmpty(updateOrderCraftEntities)) {
            if(updateOrderEntities.size()> 2000){
                List<List<OrderCraftEntity>> updateOrderCraftLists = CommonUtil.groupList(updateOrderCraftEntities);
                updateOrderCraftLists.forEach(updateOrderCraftList ->orderCraftMapper.updateBatchById(updateOrderCraftList));
            }else{
                orderCraftMapper.updateBatchById(updateOrderCraftEntities);
            }
        }
        if(CollectionUtil.isNotEmpty(updateTaskList)){
            if(updateTaskList.size() > 2000){
                List<List<MachineToolTaskEntity>> updateTaskLists = CommonUtil.groupList(updateTaskList);
                updateTaskLists.forEach(groupUpdateTaskList -> machineToolTaskMapper.updateBatchById(groupUpdateTaskList));
            }else{
                machineToolTaskMapper.updateBatchById(updateTaskList);
            }
        }
        inventoryTask.abutmentProductionReload(materialNos);
        return Boolean.TRUE;
    }

    private void addMaterialNos(List<String> materialNos, String materialNo) {
        QueryWrapper<ProductionBomEntity> wrapper = new QueryWrapper<>();
        wrapper.eq("figure_no", materialNo);
        List<ProductionBomEntity> productionBomEntities = productionBomMapper.selectList(wrapper);
        if (CollectionUtil.isEmpty(productionBomEntities)) {
            materialNos.add(materialNo);
        }
    }

    private void addMaterialNosReload(List<String> materialNos,Map<String , List<ProductionBomEntity>> productionBomEntityMap, String materialNo) {
        List<ProductionBomEntity> productionBomEntities = productionBomEntityMap.get(materialNo);
        if (CollectionUtil.isEmpty(productionBomEntities)) {
            materialNos.add(materialNo);
        }
    }

    public Object updateInCraftBz(UpdateInCraftBzReq updateInCraftBzReq) throws ToolManageException {
        List<CraftParamVo> craftParamVos = queryOrderCraftDetail(updateInCraftBzReq.getTaskId());
        if (CollectionUtil.isNotEmpty(craftParamVos)) {
            craftParamVos.forEach(craftParamVo -> {
                if (craftParamVo.getSeq() == updateInCraftBzReq.getSeq()) {
                    craftParamVo.setBz(updateInCraftBzReq.getBz());
                }
            });
            QueryWrapper<OrderCraftEntity> wrapper = new QueryWrapper<>();
            wrapper.eq("task_id", updateInCraftBzReq.getTaskId());
            OrderCraftEntity orderCraftEntity = orderCraftMapper.selectOne(wrapper);
            orderCraftEntity.setCraftParam(JSONArray.toJSONString(craftParamVos));
            orderCraftMapper.updateById(orderCraftEntity);
        }
        return Boolean.TRUE;
    }


    public Object queryOrderListReload1(QueryOrderReq queryOrderReq) {
        List<OrderEntity> orderEntities = queryOrderListReload(queryOrderReq);
        List<OrderEntity> pageList = new ArrayList<>();
        List<String> taskIds = machineToolTaskRespository.selectGroupTaskId(new ArrayList<>());
        if (CollectionUtil.isEmpty(taskIds)) {
            return new PageResult<>(new ArrayList<>(), 0L);
        }
        orderEntities = orderEntities
                .stream()
                .filter(orderEntity -> taskIds.contains(orderEntity.getTaskId()))
                .collect(Collectors.toList());
        pageList = CommonUtil.pageList(orderEntities, queryOrderReq.getPageNum(), queryOrderReq.getPageSize());
        return new PageResult<>(pageList, (long) orderEntities.size());
    }

    public List<String> getAllTaskIds() {
        QueryWrapper<OrderEntity> orderWrapper = new QueryWrapper<>();
        orderWrapper.ne("abutment_status" , 9);
        List<OrderEntity> orderEntities = orderMapper.selectList(orderWrapper);
        return orderEntities.stream().map(OrderEntity::getTaskId).collect(Collectors.toList());
    }


    public void exportOrderTemplate(HttpServletResponse response) {
        String outputFileName = "工单导入模版";
        CommonUtil.exportExcelFile(new Object() , "/template/order/工单导入模版.xlsx" , response , outputFileName);
    }

    public Object setOrderCraftTypeFlag() {
        //QueryWrapper<OrderCraftEntity> wrapper = new QueryWrapper<>();
        List<OrderCraftEntity> updateList = new ArrayList<>();
        List<OrderCraftEntity> orderCraftEntities = orderCraftMapper.selectList(new QueryWrapper<>());
        orderCraftEntities.forEach(orderCraftEntity -> {
            if(StringUtils.isNotBlank(orderCraftEntity.getCraftParam())){
                List<CraftParamVo> craftParamVoList = JSONArray.parseArray(orderCraftEntity.getCraftParam(), CraftParamVo.class);
                if(CollectionUtil.isNotEmpty(craftParamVoList)){
                    craftParamVoList.forEach(craftParamVo -> {
                        if(ObjectUtil.isNull(craftParamVo.getTypeFlag())){
                            //相等为0  不相等为1
                            if (Objects.equals(craftParamVo.getCraftPlanNumber(), craftParamVo.getCraftUnallocatedNumber())) {
                                craftParamVo.setTypeFlag(0);
                            } else {
                                craftParamVo.setTypeFlag(1);
                            }
                        }
                    });
                    orderCraftEntity.setCraftParam(JSONArray.toJSONString(craftParamVoList));
                    updateList.add(orderCraftEntity);
                }
            }
        });
        if(CollectionUtil.isNotEmpty(updateList)){
            if(updateList.size()>2000){
                List<List<OrderCraftEntity>> lists = CommonUtil.groupList(updateList);
                lists.forEach(list->orderCraftMapper.updateBatchById(list));
            }else {
                orderCraftMapper.updateBatchById(updateList);
            }
        }
        return Boolean.TRUE;
    }
}
